package com.shark.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class FairLockNumberAndLetterPrint {
    private final ReentrantLock lock = new ReentrantLock(true); // 创建一个公平锁
    private final Condition printDigitCondition = lock.newCondition();
    private final Condition printLetterCondition = lock.newCondition();

    private boolean printDigitTurn = true; // 初始时轮到打印数字
    private int digitCount = 1; // 数字计数器

    public void printDigits() {
        while (digitCount <= 52) { // 打印两次数字
            lock.lock();
            try {
                while (!printDigitTurn) {
                    printDigitCondition.await(); // 等待打印数字的信号
                }

                // 打印两位数字
                System.out.print(digitCount++);
                System.out.print(digitCount++);

                printDigitTurn = false; // 轮到打印字母
                printLetterCondition.signal(); // 通知打印字母的线程
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }

    public void printLetters() {
        for (char c = 'A'; c <= 'Z'; c++) { // 打印三次字母
            lock.lock();
            try {
                while (printDigitTurn) {
                    printLetterCondition.await(); // 等待打印字母的信号
                }

                // 打印字母
                System.out.println(c);
                printDigitTurn = true; // 轮到打印数字
                printDigitCondition.signal(); // 通知打印数字的线程
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        FairLockNumberAndLetterPrint ap = new FairLockNumberAndLetterPrint();

        Thread t1 = new Thread(ap::printDigits, "Digit-Printer");
        Thread t2 = new Thread(ap::printLetters, "Letter-Printer");

        t1.start();
        t2.start();
    }
}